package org.splink.library.logging {
	/**
	 * @author maxmc
	 */
	internal class StackParser {
		/**
		 * Creates a stacktrace and extracts the classname, methodname & line number of the given line 
		 * 
		 * @param lineNr the line of the stacktrace to analyze
		 * @return a <code>StackTrace</code> instance
		 */
		public static function getStackTrace(className : String, lineNr : int) : StackTrace {
			var stackTrace : String = new Error().getStackTrace();
			if (stackTrace == null) {
				return new StackTrace(className, "", 0);
			}

			var methodName : String = "undetectableMethod";
			var slash : String = "/";

			var line : String = stackTrace.split("\n")[lineNr];
			if (line) {
				if (line.indexOf("<anonymous>") != -1) {
					methodName = "anonymous";
				} else if (line.indexOf("at ") != -1) {
					var a : String = line.split("at ")[1];
					if (a && a.indexOf(slash) != -1)
						className = a.split(slash)[0];
				}
				className = className.replace("()", "").replace("::", ".").replace("[", "");

				if (line.indexOf("<anonymous>") == -1) {
					if (line.indexOf("()") != -1) {
						var b : String = line.split("()")[0];
						if (b && b.indexOf(slash) != -1) {
							methodName = b.split(slash)[1];
						} else {
							if (className.indexOf(".") != -1)
								methodName = className.substr(className.indexOf(".") + 1, className.length);
							else methodName = className;
						}
					}
				}

				var lineNumber : String = "0";
				if (line.indexOf(".as:") != -1) {
					var c : String = line.split(".as:")[1];
					if (c && c.indexOf("]") != -1) {
						lineNumber = c.split("]")[0];
					}
				}
			}

			return new StackTrace(className, methodName, parseInt(lineNumber));
		}
	}
}